package auction.securechannel;


import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

import org.apache.log4j.Logger;
import org.bouncycastle.util.encoders.Base64;

public class Base64Channel extends ChannelDecorator{
	public static Logger log = Logger.getLogger(Base64Channel.class);


	public Base64Channel(Channel decoratedChannel) {
		super(decoratedChannel);
	}

	@Override
	public void send(byte[]  message)  {
		try {
			String temp = new String (message);
			//log.debug("temp-send-base64channel: "+temp);
			if (!(temp.startsWith("!list") || temp.startsWith("!end") || temp.startsWith("!exit")||temp.startsWith("Invalid Command")))
				message = encode(message);
		} catch (UnsupportedEncodingException e) {
			log.debug("Error: "+e.getMessage());
		}
		decoratedChannel.send(message);

	}

	private byte[]  encode(byte[]  message) throws UnsupportedEncodingException {
		// encode into Base64 format 
		byte[] encryptedMessage = message; 
		byte[] base64Message = Base64.encode(encryptedMessage);
		return base64Message;
	}

	@Override
	public byte[] receive()  {

		try {
			byte[] message = decoratedChannel.receive();
			if(message!=null){
				String temp = new String (message);

				//log.debug("temp-receive-base64: "+temp);
				if (!(temp.startsWith("!list") || temp.startsWith("!end") || temp.startsWith("!exit")||temp.startsWith("Invalid Command")))
					return decode(message);
				else 
					return message;
			}
		} catch (UnsupportedEncodingException e) {
			log.debug("Error: "+e.getMessage());
		}
		return null;
	}

	private byte[]  decode(byte[]  message) throws UnsupportedEncodingException {
		// decode from Base64 format 
		byte[] base64Message = message;
		if(message.length>0){
			byte[]	encryptedMessage = Base64.decode(base64Message);
			return encryptedMessage;
		}
		return message;
		
	}

	public PublicKey getPublicKey() {

		return decoratedChannel.getPublicKey();
	}
	public void setPublicKey(PublicKey publicKey) {
		decoratedChannel.setPublicKey(publicKey);
	}
	public  PrivateKey getPrivateKey() {
		return decoratedChannel.getPrivateKey();
	}
	public  void setPrivateKey(PrivateKey privateKey) {
		decoratedChannel.setPrivateKey(privateKey);
	}

	public SecretKey getSecretKey() {
		return decoratedChannel.getSecretKey();
	}

	public void setSecretKey(SecretKey secretKey) {
		this.decoratedChannel.setSecretKey(secretKey);
	}

	public IvParameterSpec getIvParameter() {
		return decoratedChannel.getIvParameter();
	}

	public void setIvParameter(IvParameterSpec ivParameter) {
		this.decoratedChannel.setIvParameter(ivParameter);
	}
	public void closeSocket(){
		decoratedChannel.closeSocket();
	}

}
